<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/4 0004
 * Time: 下午 3:11
 */
namespace app\admin\controller;
use app\admin\model\Orderconf;
use app\admin\model\Recordconsumption;
use app\common\BaseHelper;
use app\lib\dadaapi\ToolsInco;
use app\common\DictConstant;
use app\common\model\Order as OrderModel;
use app\common\model\Orderproductdetail;
use app\common\model\Querydeliverfee;
use app\common\model\Refundorder;
use app\common\validate\DeliverGoods;
use app\common\validate\TenantRefund;
use app\lib\exception\ParameterException;
use app\admin\model\Operator as OperatorModel;
use distribution\DadaAddOrder;
use think\Db;
use think\Exception;
use think\Request;


class Order extends Base
{

    public function index(){
        if(!$this->checkStore()) {
            return $this->fetch('public/alert');
        }
        
        $request = Request::instance();
        $param = $request->param();
        $tenantId = session('TENANT_ID');
        // 获取所有门店
        $store = model('store')->where(['tenantId'=>$tenantId])->order('createDate')->select();
        $storeId = isset($param['id']) ? $param['id'] : $store[0]['id'];

        $this->assign('store',$store);
        $this->assign('storeId',$storeId);

        return $this->fetch();
    }

    /**
     * 获取所有订单
     */
    public function getOrderList(){
        $request = $this->request;
        $param = $request->param();

        if(session('member')['roleType'] == 2 ) {
            $storeId = session('member')['storeId'];
        } else {
            $store = model('store')->where(['tenantId' => session('TENANT_ID')])->order('createDate')->find();
            $storeId = $store->id;
        }

        $start = $param['start'];  // 每页起始条数
        $length = $param['length'];  // 每页显示条数
        $columns = $param['order'][0]['column'];
        $order = $param['columns'][$columns]['data'].' '.$param['order'][0]['dir'];  //排序条件

        if($param['storeId']){
            $storeId = $param['storeId'];
        }
        $where = [
            'tenantId' => session('TENANT_ID'),
            //'linkType' => 0,
            'linkType' => ['in', '0, 1, 2'],
            'storeId' => $storeId
        ];
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);
            if($filter['storeId']){
                $where['storeId'] = $filter['storeId'];
            }
            if($filter['linkType'] || $filter['linkType'] == '0'){
                $where['linkType'] = $filter['linkType'];
            }
            if(isset($filter['status']) && $filter['status']){
                $where['status'] = $filter['status'];
            }
            if(isset($filter['orderNO']) && trim($filter['orderNO'])){
                $where['orderNO'] = ['like', '%' . trim($filter['orderNO']) . '%'];
            }
            if(isset($filter['begin_time']) && $filter['begin_time']){
                $where['create_time'] = ['egt', strtotime($filter['begin_time'])];
            }
            if(isset($filter['end_time']) && $filter['end_time']){
                //$where['create_time'] = ['elt', strtotime($filter['end_time'])];
                $where['create_time'] = ['lt', strtotime($filter['end_time']) + 24*60*60];
            }
            if(isset($filter['begin_time']) && $filter['begin_time'] && isset($filter['end_time']) && $filter['end_time']){
                //$where['create_time'] = [['egt', strtotime($filter['begin_time'])], ['elt', strtotime($filter['end_time'])], 'and'];
                $where['create_time'] = [['egt', strtotime($filter['begin_time'])], ['lt', strtotime($filter['end_time']) + 24*60*60], 'and'];
            }
        }

        $list = OrderModel::where($where)->limit($start, $length)->order($order)->select();
        foreach ($list as $key => $val) {
            $item = $list[$key];
            $item->productImg = isset($val->orderproductDetail[0]['productImg']) ? $val->orderproductDetail[0]['productImg'] : '';
        }
        $count = OrderModel::where($where)->count();

        $result = [
            'status' => '1',
            'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
        ];

        return json($result);
    }

    /**
     * 导出数据
     */
    public function export(){
        $param = $this->request->param();

        $where = [
            'tenantId' => session('TENANT_ID'),
            //'linkType' => 0,
            'linkType' => ['in', '0, 1, 2'],
        ];
        if(!empty($param['storeId'])){
            $where['storeId'] = $param['storeId'];
        }
        if($param['linkType'] || $param['linkType'] == '0'){
            $where['linkType'] = $param['linkType'];
        }
        if(!empty($param['status'])){
            $where['status'] = $param['status'];
        }
        if(!empty($param['orderNO'])){
            $where['orderNO'] = ['like', '%'.$param['orderNO'].'%'];
        }
        if(!empty($param['begin_time'])){
            $where['create_time'] = ['egt', strtotime($param['begin_time'])];
        }
        if(!empty($param['end_time'])){
            $where['create_time'] = ['elt', strtotime($param['end_time'])];
        }
        if(!empty($param['begin_time']) && !empty($param['end_time'])){
            //$where['create_time'] = [['egt', strtotime($param['begin_time'])], ['elt', strtotime($param['end_time'])], 'and'];
            $where['create_time'] = [['egt', strtotime($param['begin_time'])], ['lt', strtotime($param['end_time']) + 24*60*60], 'and'];
        }

        //$data = OrderModel::where($where)->order('create_time', 'asc')->limit(1000)->select();
        $data = OrderModel::where($where)->order('create_time', 'asc')->select();
        if(count($data) <= 0){
            $this->error('没有数据！', url('admin/order/index'));
        }
        foreach ($data as $key => $val) {
            // 图片
            $val['productImg'] = isset($val->orderproductDetail[0]['productImg']) ? $val->orderproductDetail[0]['productImg'] : '';
            // 支付方式
            if($val['payMethod'] == 0){
                $val['payMethod'] = '微信支付';
            }else{
                $val['payMethod'] = '余额支付';
            }
            // 订单金额
            $val['total'] = $val['total'] / 100 . ' 元';
            // 订单状态
            switch ($val['status']) {
                case 1: $val['status'] = '待付款'; break;
                case 2: $val['status'] = '待发货'; break;
                case 3: $val['status'] = '待收货'; break;
                case 4: $val['status'] = '已完成'; break;
                case 5: $val['status'] = '已失效'; break;
                case 6: $val['status'] = '售后'; break;
                case 7: $val['status'] = '已消费'; break;
                case 8: $val['status'] = '未消费'; break;
                case 9: $val['status'] = '拼团中'; break;
                case 10: $val['status'] = '同意售后退款'; break;
                default : $val['status'] = '拒绝售后退款'; break;
            }
        }
        $cellName = array(
            'A' => ['productImg', '图片'],
            'B' => ['orderNO', '订单号'],
            'C' => ['total_count', '商品数量'],
            'D' => ['payMethod', '支付方式'],
            'E' => ['total', '订单金额(元)'],
            'F' => ['userPhone', '手机号'],
            'G' => ['create_time', '下单时间'],
            'H' => ['status', '订单状态'],
        );

        $filePath = ROOT_PATH . 'public' . DS . 'upload' . DS . 'csv' . DS . 'order' . DS . date('Y-m-d');
        $fileName = $filePath . '/order_' . date('y-m-d-H-i-s');

        $excel = new Excel();
        $excel->exportExcel('订单', $data, $cellName, $filePath, $fileName);

        return redirect('admin/order/index');
    }


    /**
     * @param $id
     * 添加达达配送订单
     */
    /*public function getAdders($id){
        $addOrder = new DadaAddOrder();
        $orderModel = new OrderModel();
        $orderModel->getCurrentOrder($id);
        $dataParam['orderId'] = $id;
        $dataParam['address'] = "";
        $addOrder->addOrder($dataParam);

    }*/

    /**
     * @param $param
     * @return bool|string
     * 参数序列化
     */
    public function paramSerialize($param){
        $paramStr = "?";
        foreach ($param as $key=>$item){
            $paramStr = $paramStr.$key."=".$item."&";
        }

        return $paramStr;
    }


    /**
     *获取达达预配送订单
     */
    public function queryDeliverFee(){
        $id = input('post.id');
        $tenantId = session("TENANT_ID");
        $Tenant = \app\admin\model\Tenant::get($tenantId);
        $dadaBalance = $Tenant->dadaBalance;
        if(!$id) {
            return show(config('status.ERROR_STATUS'), '参数id不能为空', array("id" => $id));
        }
        $orderModel = new \app\common\model\Order();
        $tools = new ToolsInco();
        $config = $tools->getDataConfig();
        $order = $orderModel->getCurrentOrder($id);
        if($order && !empty($order) && $order->status==2){
            $userAddress  = $order->deliverAddress;
        }else{
            return show(config('status.ERROR_STATUS'),'无效订单或者订单已经发货',array("order"=>$order));
        }


        if($order->type == $orderModel:: STATUS_VALID){ //线下订单
            return show(config('status.ERROR_STATUS'),'线下订单不支持达达配送',array("order"=>$order));
        }

        $data['address']=$userAddress;
        $is_prepay = $tools::is_prepay_0;//是否需要垫付 1:是 0:否 (垫付订单金额，非运费)
        $data['shop_no'] = $order->storeId;
        $data['is_prepay'] = $is_prepay;
        //根据地址获取收货人经纬度
        $dadaAddOrder = new DadaAddOrder();
        $TencentLatLng = BaseHelper::GeocoderAddress($data['address']); //腾讯地图和高德地图使用的是同一坐标系
        //$gaodeResult = $dadaAddOrder->getAddres(["address"=>$data["address"]]);

        //$res = json_decode($gaodeResult);
//        if($res->status == $orderModel::STATUS_INVALID){
//            return show(config('status.ERROR_STATUS'),'用户地址参数错误！收货人地址不能为空！',array("cityName"=>""));
//        }

        $cityName = $TencentLatLng['address_components']['city'];;
        if(isset($cityName) && !empty($cityName)){
            //获取城市编码
            $city_code = $dadaAddOrder->getCityCode(['cityName'=>$cityName]);
        }else{
            return show(config('status.ERROR_STATUS'),'用户所在城市不能为空！',array("cityName"=>""));
        }
        $receiver_name = $order->userName;                       //收货人
        $mobile = $order->userPhone;                             //收货人手机号码
        if($receiver_name == "" || !$receiver_name){
            return show(config('status.ERROR_STATUS'),'收货人不能为空！',$receiver_name);
        }
        if($mobile == "" || !$mobile){
            return show(config('status.ERROR_STATUS'),'收货人电话不能为空！',"");
        }
        $cargo_price = $order->total;
        $origin_id = $id;
        $receiver_lat = $TencentLatLng['location']['lat'];    //收货人地址经度
        $receiver_lng = $TencentLatLng['location']['lng'];    //收货人地址纬度
        $receiver_address = $data['address'];
        $callback = config('miniprogram.domain').'/api/DadaNotify/index';
        $data['origin_id'] =$origin_id;
        $data['city_code'] = $city_code->cityCode;
        $data['cargo_price'] = sprintf("%.2f",$cargo_price/100);
        $data['receiver_name'] = $receiver_name;
        $data['receiver_address'] = $receiver_address;
        $data['callback'] = $callback;
        $data['receiver_phone'] = $mobile;     //收货人手机号
        $data['$receiver_lat'] = $receiver_lat;     //收货人手机号
        $data['$receiver_lng'] = $receiver_lng;     //收货人手机号
        $data['tips'] = 0;     //收货人手机号
        $dadaAddOrder = new DadaAddOrder();
        $result = $dadaAddOrder->queryDeliverFee($data);
        if($result['code'] == 0 && $result['status'] == 'success'){
            $result = $result['result'];
        }else{
            return show(config('status.ERROR_STATUS'),'连接达达服务器异常','连接达达服务器异常');
        }
        if($dadaBalance < ($result['fee']*100)){
            return show(config('status.DADA_Short_freight'),'达达运费不足，请充值达达运费','达达运费不足');
        }
        $result['order_id'] = $order->id;
        $querydeliverfeeModel = new Querydeliverfee();
        $dataParam['createDate'] = date('Y-m-d h:i:s',time());
        $dataParam['createOper'] = $tenantId;
        $dataParam['order_id'] = $order->id;
        $dataParam['createOper'] = $tenantId;
        $dataParam['id'] = get_uniqid_id();
        $dataParam['distance'] = round($result['distance']);
        $dataParam['fee'] = round($result['fee']);
        $dataParam['deliverFee'] = $result['deliverFee'];
        $dataParam['deliveryNo'] = $result['deliveryNo'];
        $res = $querydeliverfeeModel->insterQueryDeliverFee($dataParam);
        return show(config('status.SUCCESS_STATUS'),'获取订单运费成功！',$result);
    }

    /**
     * @return \think\response\Json
     * 提交哒哒预配送订单
     */
    public function addAfterQuery(){
        $deliveryNo = input('post.deliveryNo');
        $param['deliveryNo'] = $deliveryNo;
        $orderId = input('post.orderId');
        $fee = input('post.fee');
        $storeId = input('post.storeId');
        $Order = \app\common\model\Order::get($orderId);
        $Tenant = \app\admin\model\Tenant::get($Order->tenantId);
        if($deliveryNo && !empty($deliveryNo)){
            $dada = new DadaAddOrder();
            //再次检测达达运费是否充足
            if($Tenant->dadaBalance < $fee*100){
                return show(config('status.ERROR_STATUS'),'达达运费不足，请充值达达运费',"提交配送订单失败");
            }
            $result = $dada->addAfterQuery($param);
            if($result['code'] == 0){
                //扣除商户达达运费
                $Tenant->setDec('dadaBalance',$fee*100);
                //插入消费记录
                $data = [
                    'tenantId' => $Tenant->id,
                    'orderId' => $orderId,
                    'money' => $fee*100,
                    'type' => 2,
                ];
                $this->insertrecordconsumption($data);
                return show(config('status.SUCCESS_STATUS'),'提交配送订单成功',$result);
            }else{
                return show(config('status.ERROR_STATUS'),'提交配送订单失败',$result);
            }
        }else{
            return show(config('status.ERROR_STATUS'),'哒哒预提交订单获取失败',array(
                "orderNo"=>$deliveryNo
            ));
        }
    }

    private function insertrecordconsumption($data){
        $Recordconsumption = new Recordconsumption();
        $Recordconsumption->id = BaseHelper::getUUID();
        $Recordconsumption->tenantId = $data['tenantId'];
        $Recordconsumption->record_type = $data['type'];
        $Recordconsumption->money = $data['money'];
        $Recordconsumption->orderId = $data['orderId'];
        $Recordconsumption->save();
    }

    /**
     * 订单详情
     * @param $id
     * @return mixed
     * @throws ParameterException
     */
    public function OrderDetails($id){
        if(empty($id)){
            throw new ParameterException([
                'msg' => '订单号不存在'
            ]);
        }
        $ispeisong = false;
        $ordermodel = new OrderModel();
        $order = $ordermodel->where('id',$id)->find();
        $orderproductDetail = $order->orderproductDetail()->select();
        //店铺信息
        $Store = \app\admin\model\Store::get($order->storeId);
        $tenant = \app\admin\model\Tenant::get($Store->tenantId);
        $tenantname = $tenant->name . '-' . $Store->name;
        //员工
        $OperatorModel = new OperatorModel();
        $staff = $OperatorModel->where(['storeId'=>$order->storeId])->select();

        //检测订单商品是否存在售后
        foreach ($orderproductDetail as &$value){
            $Refundorder = Refundorder::where(['orderProductDetailId'=>$value['id']])->find();
            if($Refundorder){
                $value['Refundstatus'] = $Refundorder->status;
            }

        }
        $Refundorder = Refundorder::where(['orderNO'=>$order->orderNO])->where('status',['=',4],['=',0],['=',2],'OR')->select();
        if(count($orderproductDetail)>count($Refundorder)){
            $ispeisong = true;
        }
        //判断该订单是否可以配送
        //status = 2 11

        if($order->status ==2 || $order->status==11){
            $ispeisong = true;
        }
        if($order->status == 3 || $order->status == 4){
            $ispeisong = false;
        }
        //获取订单配送信息
        $tenantId = $order->tenantId;
        $Tenantdistributiontype = \app\admin\model\Tenantdistributiontype::where(['tenantId'=>$tenantId,'distributionType'=>2,'status'=>1])->find();

        $this->assign('id',$id);
        $this->assign('order',$order);
        $this->assign('staff',$staff);
        $this->assign('orderproductDetail',$orderproductDetail);
        $this->assign('Distributionmode',$Tenantdistributiontype);
        $this->assign('tenantname',$tenantname);
        $this->assign('ispeisong',$ispeisong);
        //return show(1,'ok',$Tenantdistributiontype);
        return $this->fetch();

    }

    /**
     * 处理订单发货
     * @return \think\response\Json
     * @throws ParameterException
     */
    public function DoDelivergoods(){
        if(request()->isPost()) {
            Db::startTrans();
            try {

                (new DeliverGoods())->goCheck();
                $ispeisong = false;
                $order = \app\common\model\Order::get(input('post.id'));
                if($order->status ==2 || $order->status==11){
                    $ispeisong = true;
                }
                $orderproductDetail = $order->orderproductDetail()->select();
                $Refundorder = Refundorder::where(['orderNO'=>$order->orderNO])->where('status',['=',4],['=',0],['=',2],'OR')->select();
                if(count($orderproductDetail)>count($Refundorder)){
                    $ispeisong = true;
                }
                if ($order && $ispeisong) {
                    $order->deliverDate = date('Y-m-d H:i:s', time());
                    $order->status = DictConstant::OrderAlreadyShipped;
                    $isfahuo = [
                        'status' => 0,
                        'message' => '发货失败',
                        'data' => '发货失败'
                    ];
                    if (input('post.deliverMethod') == 1) {  //商家自行配送
                        $order->deliverMethod = input('post.deliverMethod');
                        $operator = \app\admin\model\Operator::get(input('post.deliverUserName'));
                        if ($operator) {
                            $order->deliverUserName = $operator->name;
                            $order->deliverUserPhone = $operator->phone;
                        } else {
                            throw new ParameterException([
                                'msg' => '配送员不存在'
                            ]);
                        }
                        if (input('post.expecteddelivery') != 0) {

                            $time = $this->expecteddelivery(input('post.expecteddelivery'));
                            $order->expecteddelivery = $time;
                            $order->deliverMethod = 1;

                        }
                        if ($order->save()) {
                            $isfahuo['status'] = 1;
                            $isfahuo['message'] = '发货成功';
                            $isfahuo['data'] = '发货成功';
                        }

                    } elseif (input('post.deliverMethod') == 0) {  //物流配送
                        $order->expressName = input('post.expressName');
                        $order->expressNo = input('post.expressNo');
                        $order->deliverMethod = 0;


                        if ($order->save()) {
                            $isfahuo['status'] = 1;
                            $isfahuo['message'] = '发货成功';
                            $isfahuo['data'] = '发货成功';
                        }
                    } else {

                    }
                    $Orderproductdetail = new Orderproductdetail();
                    $orderpro = $Orderproductdetail->where('orderId', $order->id)->select();
                    $list = [];
                    foreach ($orderpro as $value) {
                        array_push($list, ['id' => $value['id'], 'oldStatus' => DictConstant::OrderAlreadyShipped]);
                    }
                    $Orderproductdetail->saveAll($list);
                } else {
                    if($order && $order->status == DictConstant::Order_GroupIng){
                        throw new ParameterException([
                            'msg' => '拼团中的订单不能发货'
                        ]);
                    }
                    throw new ParameterException([
                        'msg' => '订单不存在或者订单已经发货'
                    ]);
                }
                Db::commit();
                return show(config('status.SUCCESS_STATUS'),'ok',$isfahuo);

            } catch (Exception $ex) {
                Db::rollback();
                return show(config('status.ERROR_STATUS'),$ex->msg,$ex->msg);
            }
        }
    }

    public function config(){
        $tenantId = session('TENANT_ID');
        $orderconf = Orderconf::get($tenantId);
        if($orderconf){
            $this->assign('invalid_time',$orderconf->invalid_time);
            $this->assign('confirm_time',$orderconf->confirm_time);
        }else{
            $this->assign('invalid_time',0);
            $this->assign('confirm_time',0);
        }
        $this->assign('tenantId',$tenantId);

        if(request()->isPost()){
            if($orderconf){
                $orderconf->invalid_time = input('post.invalid_time');
                $orderconf->confirm_time = input('post.confirm_time');
                $orderconf->save();
                return show(config('status.SUCCESS_STATUS'),'修改成功','修改成功');
            }else{
                $orderconf = new Orderconf();
                $orderconf->tenantId = input('post.tenantId');
                $orderconf->invalid_time = input('post.invalid_time');
                $orderconf->confirm_time = input('post.confirm_time');
                $orderconf->save();
                return show(config('status.SUCCESS_STATUS'),'添加成功','添加成功');
            }

        }
        return $this->fetch();
    }


    private function expecteddelivery($yj){
        if($yj == 1){
            $time = time() + 30*60;
        }elseif ($yj == 2){
            $time = time() + 60*60;
        }elseif ($yj == 3){
            $time = time() + 3*60*60;
        }elseif ($yj == 4){
            $time = time() + 24*60*60;
        }elseif ($yj == 5){
            $time = time() + 48*60*60;
        }else{
            $time = time() + 72*60*60;
        }
        return $time;

    }

    public function reAddOrder(){

    }

    private function queryStatusName($result){
        switch ($result->status){
            case 1:
                return "等待起手接单";
            case 2:
                return "待取货";
            case 3:
                return "配送中";
            case 4:
                return "已完成";
            case 5:
                return "已取消";
            case 7:
                return "已过期";
            case 8:
                return "指派单";
            case 9:
                return "妥投异常之物品返回中";
            case 10:
                return "妥投异常之物品返回完成";
            case 1000:
                return "创建达达运单失败";
        }
    }


    /**
     * @return \think\response\Json
     * 哒哒配送物流跟踪
     */
    public function orderQuery(){
        $order_id = input('order_id');
        $DadaAddOrder = new DadaAddOrder();
        $QueryDeliverFeeModel = new Querydeliverfee();
        $QueryDeliverFee = $QueryDeliverFeeModel->findQueryDeliver($order_id);
        if($QueryDeliverFee && !empty($QueryDeliverFee)){
            if($QueryDeliverFee->status == $QueryDeliverFeeModel::status_1){
                //返回失败
                $returnData['code'] ="0";
                $returnData['orderStatus'] =$QueryDeliverFee->status;
                $returnData['orderStatusName'] ="等待起手接单";
                return show(config('status.SUCCESS_STATUS'),'获取物流跟踪状态成功',$returnData);
            }
        }
        $result = $DadaAddOrder->addAfterQuery($order_id);
        if($result['code'] == 0){
            $dadaResult = $result['result'];
            $resultArr = json_decode($dadaResult,true);
            $queryStatusName = $this->queryStatusName($resultArr);
            $resultArr['statusName'] = $queryStatusName;
            $result['result'] = $resultArr;
            return show(config('status.SUCCESS_STATUS'),$result['message'],$result);
        }else{
            return show(config('status.ERROR_STATUS'),$result['message'],$result);
        }
    }
}